// task_withdraw_record_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/mine/withdrawal/record/task_withdraw_record_cell.dart';
import 'task_withdraw_record_page_vm.dart';
import '../../../../common_ui/refresh_error_alert.dart';

class TaskWithdrawRecordPage extends StatefulWidget {
  const TaskWithdrawRecordPage({Key? key}) : super(key: key);

  @override
  _TaskWithdrawRecordPageState createState() => _TaskWithdrawRecordPageState();
}

class _TaskWithdrawRecordPageState extends State<TaskWithdrawRecordPage> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => TaskWithdrawRecordPageViewModel(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('提现记录'),
          backgroundColor: Colors.white,
          elevation: 0.5,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, size: 18),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        body: _TaskWithdrawRecordContent(),
      ),
    );
  }
}

class _TaskWithdrawRecordContent extends StatefulWidget {
  @override
  __TaskWithdrawRecordContentState createState() => __TaskWithdrawRecordContentState();
}

class __TaskWithdrawRecordContentState extends State<_TaskWithdrawRecordContent> {
  @override
  void initState() {
    super.initState();
    // 在子widget的initState中调用，此时Provider已经创建
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<TaskWithdrawRecordPageViewModel>().refresh();
    });
  }

  Widget _buildLoadMoreIndicator(TaskWithdrawRecordPageViewModel viewModel) {
    if (viewModel.isLoading && viewModel.hasMore) {
      return const Padding(
        padding: EdgeInsets.all(16),
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    if (!viewModel.hasMore && viewModel.monthList.isNotEmpty) {
      return const Padding(
        padding: EdgeInsets.all(16),
        child: Center(
          child: Text(
            '没有更多数据了',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
        ),
      );
    }

    return Container();
  }

  Widget _buildListView(TaskWithdrawRecordPageViewModel viewModel) {
    if (viewModel.isLoading && viewModel.monthList.isEmpty) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (viewModel.monthList.isEmpty && viewModel.errorType != null) {
      return RefreshErrorAlert(
        type: viewModel.errorType!,
        tip: viewModel.errorType == LoadErrorType.noData ? '暂无记录' : '网络错误',
      );
    }

    return ListView.builder(
      itemCount: viewModel.monthList.length + (viewModel.hasMore ? 1 : 0),
      itemBuilder: (context, index) {
        // 如果是最后一个item且需要显示加载更多指示器
        if (index == viewModel.monthList.length) {
          return _buildLoadMoreIndicator(viewModel);
        }

        // 正常的数据item
        final record = viewModel.monthList[index];
        final showLine = index < viewModel.monthList.length - 1;

        return TaskTransactionRecordCell(
          record: record,
          showLine: showLine,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<TaskWithdrawRecordPageViewModel>(
      builder: (context, viewModel, child) {
        return NotificationListener<ScrollNotification>(
          onNotification: (scrollNotification) {
            if (scrollNotification is ScrollEndNotification) {
              final metrics = scrollNotification.metrics;
              if (metrics.pixels == metrics.maxScrollExtent && !metrics.atEdge) {
                viewModel.loadMore();
              }
            }
            return false;
          },
          child: RefreshIndicator(
            onRefresh: () async => viewModel.refresh(),
            child: _buildListView(viewModel),
          ),
        );
      },
    );
  }
}